package com.itshizhan.itjidancideveloper.controller.ucenter;

import com.itshizhan.itjidancideveloper.dao.WordRootDao;
import com.itshizhan.itjidancideveloper.models.WordRoot;
import com.itshizhan.itjidancideveloper.response.CodeMsgEnum;
import com.itshizhan.itjidancideveloper.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController()
@RequestMapping("/ucenter/root")
public class WordRootController {

	@Autowired
	WordRootDao wordRootDao;

	@GetMapping("/search")
	public Response<List<WordRoot>> getByKeyword(@RequestParam("q") String keyword){
		if (keyword.length() < 2) {
			return Response.fail(CodeMsgEnum.ERROR_PARAMETER);
		}
		return Response.success(wordRootDao.findByRootNameLike("%" + keyword +"%"));
	}

	@GetMapping("/detail")
	public Response<WordRoot> getDetailById(@RequestParam("id") Integer id){
		WordRoot wordRoot = wordRootDao.findById(id).orElse(null);
		return Response.success(wordRoot);
	}

	@PostMapping("/save")
	public Response<WordRoot> save(@RequestBody WordRoot wordRoot) {
		WordRoot dbRoot = wordRootDao.findById(wordRoot.getId()).orElse(null);
		if (dbRoot!=null){
			dbRoot.setMemoryMd(wordRoot.getMemoryMd());
			dbRoot.setMemoryHtml(wordRoot.getMemoryHtml());
			WordRoot root = wordRootDao.save(dbRoot);
			return Response.success(root);
		}
		return Response.fail();

	}
}
